/*
 * Copyright (c) Tan Menglong.
 * All rights reserved.
 * 
 * This file is part of the RabbitOS.  The RabbitOS is free software, also known
 * as "open source;" you can redistribute it and/or modify it under the terms
 * of the GNU General Public License (GPL), version 2, as published by the Free
 * Software Foundation (FSF).  To explore alternate licensing terms, contact
 * the Tan Menglong at TanMenglong@gmail.com or +86-15972108715.
 * 
 * The RabbitOS is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GPL for more details.  You should have
 * received a copy of the GPL along with the RabbitOS; see the file COPYING.  If
 * not, write to the FSF, 59 Temple Place #330, Boston, MA 02111-1307, USA.
 */
/*
 * Interupt Service Routine.
 * 09-Jun-08
 */

#include <global.h>
#include <init/isr.h>
#include <sys/types.h>
#include <stddef.h>

isr_t interrupt_handlers[256];

void send_eoi(int int_no)
{
	// Send an EOI (end of interrupt) signal to the PICs.
	// If this interrupt involved the slave.
	if (int_no >= 40) {
		// Send reset signal to slave.
		outb(0xA0, 0x20);
	}
	// Send reset signal to master. (As well as slave, if necessary).
	outb(0x20, 0x20);
}

void register_interrupt_handler(u8int n, isr_t handler)
{
	interrupt_handlers[n] = handler;
}

// This gets called from our ASM interrupt handler stub.
void isr_handler(registers_t regs)
{
	// This line is important. When the processor extends the 8-bit interrupt number
	// to a 32bit value, it sign-extends, not zero extends. So if the most significant
	// bit (0x80) is set, regs.int_no will be very large (about 0xffffff80).
	u8int int_no = regs.int_no & 0xFF;
	if (interrupt_handlers[int_no] != NULL) {
		isr_t handler = interrupt_handlers[int_no];
		handler(regs);
	} else {
		printk("unhandled interrupt: %x\n",int_no);
		crash("Unhandled interrupt.");
		//for (;;);
		//TODO: Add panic()
	}

	send_eoi(regs.int_no);
}

// This gets called from our ASM interrupt handler stub.
void irq_handler(registers_t regs)
{
	if (interrupt_handlers[regs.int_no] != NULL) {
		isr_t handler = interrupt_handlers[regs.int_no];
		handler(regs);
	}

	send_eoi(regs.int_no);
}

